package com.lxw.nonghe.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.Claims;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxw.nonghe.annotation.RequiresPermission;
import com.lxw.nonghe.common.RegionStat;
import com.lxw.nonghe.common.Result;
import com.lxw.nonghe.entity.*;
import com.lxw.nonghe.service.*;
import com.lxw.nonghe.util.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 慢病报销控制器
 */
@RestController
@RequestMapping("/chronicDiseaseReimbursement")
@RequiresPermission("reimbursement:manage")
public class ChronicDiseaseReimbursementController {

    @Autowired
    private ChronicDiseaseReimbursementService reimbursementService;

    @Autowired
    private FarmerService farmerService;

    @Autowired
    private ChronicDiseaseCertificateService certificateService;

    @Autowired
    private ChronicDiseasePolicyService policyService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private AdministrativeRegionService administrativeRegionService;

    @Autowired
    private LogUtils logUtils;

    @PostMapping("/create")
    public Result<Boolean> addReimbursement(@RequestBody ChronicDiseaseReimbursement reimbursement) {
        try {
            // 初始化状态和时间
            reimbursement.setAuditStatus("待审核");
            reimbursement.setRemittanceStatus("待汇款");
            reimbursement.setReimbursementTime(new Date());

            // 金额类型安全转换
            if (reimbursement.getReimbursementAmount() != null) {
                reimbursement.setReimbursementAmount(new BigDecimal(reimbursement.getReimbursementAmount().toString()));
            }

            boolean result = reimbursementService.save(reimbursement);
            if (result) {
                logUtils.recordLog("慢病报销管理", "新增报销记录", "成功",
                        "农民ID:" + reimbursement.getFarmerId() + ", 金额:" + reimbursement.getReimbursementAmount());
                return Result.success("慢病报销记录新增成功", true);
            } else {
                logUtils.recordLog("慢病报销管理", "新增报销记录", "失败", "保存数据库失败");
                return Result.error("慢病报销记录新增失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "新增报销记录", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/delete/{id}")
    public Result<Boolean> deleteReimbursement(@PathVariable Integer id) {
        try {
            ChronicDiseaseReimbursement reimbursement = reimbursementService.getById(id);
            boolean result = reimbursementService.removeById(id);

            if (result) {
                logUtils.recordLog("慢病报销管理", "删除报销记录", "成功",
                        "记录ID:" + id + ", 农民ID:" + (reimbursement != null ? reimbursement.getFarmerId() : "未知"));
                return Result.success("慢病报销记录删除成功", true);
            } else {
                logUtils.recordLog("慢病报销管理", "删除报销记录", "失败", "记录ID:" + id + "不存在");
                return Result.error("慢病报销记录删除失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "删除报销记录", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    public Result<Boolean> updateReimbursement(@RequestBody ChronicDiseaseReimbursement reimbursement) {
        try {
            boolean result = reimbursementService.updateById(reimbursement);
            if (result) {
                logUtils.recordLog("慢病报销管理", "更新报销记录", "成功",
                        "记录ID:" + reimbursement.getReimbursementId());
                return Result.success("慢病报销记录更新成功", true);
            } else {
                logUtils.recordLog("慢病报销管理", "更新报销记录", "失败",
                        "记录ID:" + reimbursement.getReimbursementId() + "不存在");
                return Result.error("慢病报销记录更新失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "更新报销记录", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/audit/{id}")
    public Result<Boolean> auditReimbursement(
            @PathVariable Integer id,
            @RequestBody Map<String, Object> requestBody) {
        try {
            // 从请求体中获取参数
            String status = (String) requestBody.get("status");
            String reason = (String) requestBody.get("reason");

            // 修正状态值校验，兼容更多可能的输入
            if (!("审核通过".equals(status) || "审核不通过".equals(status) || "已通过".equals(status) || "未通过".equals(status))) {
                logUtils.recordLog("慢病报销管理", "审核报销", "失败", "非法状态:" + status);
                return Result.error("非法审核状态，允许值：审核通过/审核不通过/已通过/未通过");
            }

            // 标准化状态值
            String normalizedStatus = status;
            if ("已通过".equals(status)) {
                normalizedStatus = "审核通过";
            } else if ("未通过".equals(status)) {
                normalizedStatus = "审核不通过";
            }

            ChronicDiseaseReimbursement reimbursement = new ChronicDiseaseReimbursement();
            reimbursement.setReimbursementId(id);
            reimbursement.setAuditStatus(normalizedStatus);
            //reimbursement.setAuditReason(reason);  // 确保审核原因被保存

            boolean result = reimbursementService.updateById(reimbursement);
            if (result) {
                logUtils.recordLog("慢病报销管理", "审核报销", "成功",
                        "记录ID:" + id + ", 状态:" + normalizedStatus);
                return Result.success("慢病报销审核操作成功", true);
            } else {
                logUtils.recordLog("慢病报销管理", "审核报销", "失败", "记录ID:" + id + "更新失败");
                return Result.error("慢病报销审核操作失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "审核报销", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/remittance/{id}")
    public Result<Boolean> updateRemittanceStatus(
            @PathVariable Integer id,
            @RequestBody Map<String, Object> requestBody) {
        try {
            // 从请求体中获取status参数
            String status = (String) requestBody.get("status");

            if (!("待汇款".equals(status) || "已汇款".equals(status) || "汇款失败".equals(status))) {
                logUtils.recordLog("慢病报销管理", "更新汇款状态", "失败", "非法状态:" + status);
                return Result.error("非法汇款状态，允许值：待汇款/已汇款/汇款失败");
            }

            ChronicDiseaseReimbursement reimbursement = new ChronicDiseaseReimbursement();
            reimbursement.setReimbursementId(id);
            reimbursement.setRemittanceStatus(status);

            boolean result = reimbursementService.updateById(reimbursement);
            if (result) {
                logUtils.recordLog("慢病报销管理", "更新汇款状态", "成功",
                        "记录ID:" + id + ", 状态:" + status);
                return Result.success("汇款状态更新成功", true);
            } else {
                logUtils.recordLog("慢病报销管理", "更新汇款状态", "失败", "记录ID:" + id + "更新失败");
                return Result.error("汇款状态更新失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "更新汇款状态", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @GetMapping("/get/{id}")
    public Result<ChronicDiseaseReimbursement> getReimbursementById(@PathVariable Integer id) {
        try {
            ChronicDiseaseReimbursement reimbursement = reimbursementService.getById(id);
            if (reimbursement != null) {
                /*logUtils.recordLog("慢病报销管理", "查询报销详情", "成功", "记录ID:" + id);*/
                return Result.success("慢病报销记录查询成功", reimbursement);
            } else {
                logUtils.recordLog("慢病报销管理", "查询报销详情", "失败", "记录ID:" + id + "不存在");
                return Result.error("未找到该慢病报销记录");
            }
        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "查询报销详情", "失败", e.getMessage());
            return Result.error("查询异常: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result<Page<ChronicDiseaseReimbursement>> getReimbursementPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String farmerName,
            @RequestParam(required = false) String diseaseName,
            @RequestParam(required = false) String auditStatus,
            HttpServletRequest request) {
        try {
            // 从请求头中获取 Token
            String token = request.getHeader("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error("未授权访问");
            }

            token = token.substring(7); // 去掉 "Bearer " 前缀

            // 校验 token 有效性
            if (!StpUtil.isLogin()) {
                return Result.error("无效的 Token");
            }

            // 获取登录用户 ID
            Long userId = StpUtil.getLoginIdAsLong();

            // 从 Redis 中获取用户信息
            String userKey = "user:" + userId;
            User user = (User) redisTemplate.opsForValue().get(userKey);

            if (user == null) {
                return Result.error("用户信息不存在，请重新登录");
            }

            // 从用户信息中获取行政区域编码
            String userParentCode = user.getParentCode();
            if (userParentCode == null || userParentCode.isEmpty()) {
                return Result.error("用户行政区域编码不存在");
            }

            // 调用原有的分页查询方法获取基础数据
            Page<ChronicDiseaseReimbursement> page = reimbursementService.getReimbursementPage(
                    current, size, farmerName, diseaseName, auditStatus);

            // 过滤行政区域编码符合条件的记录
            List<ChronicDiseaseReimbursement> filteredRecords = page.getRecords().stream()
                    .filter(record -> {
                        // 通过 farmerId 获取农民信息
                        Farmer farmer = farmerService.getById(record.getFarmerId());
                        if (farmer == null || farmer.getParentCode() == null) {
                            return false;
                        }

                        // 判断农民的行政区域编码是否与用户的编码相同或为其子级
                        return isValidRegionCode(userParentCode, farmer.getParentCode());
                    })
                    .collect(Collectors.toList());

            // 创建新的分页对象，包含过滤后的记录
            Page<ChronicDiseaseReimbursement> filteredPage = new Page<>(
                    page.getCurrent(),
                    page.getSize(),
                    filteredRecords.size()
            );
            filteredPage.setRecords(filteredRecords);

            return Result.success("慢病报销记录分页查询成功", filteredPage);
        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "分页查询报销", "失败", e.getMessage());
            return Result.error("分页查询异常: " + e.getMessage());
        }
    }
    @GetMapping("/list2")
    public Result<Map<String, Object>> getReimbursementPage2(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String farmerName,
            @RequestParam(required = false) String diseaseName,
            @RequestParam(required = false) String auditStatus,
            HttpServletRequest request) {
        try {
            // 身份验证部分保持不变
            String token = request.getHeader("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error("未授权访问");
            }

            token = token.substring(7);

            if (!StpUtil.isLogin()) {
                return Result.error("无效的 Token");
            }

            Long userId = StpUtil.getLoginIdAsLong();
            String userKey = "user:" + userId;
            User user = (User) redisTemplate.opsForValue().get(userKey);

            if (user == null) {
                return Result.error("用户信息不存在，请重新登录");
            }

            String userParentCode = user.getParentCode();
            if (userParentCode == null || userParentCode.isEmpty()) {
                return Result.error("用户行政区域编码不存在");
            }

            // 获取基础数据
            Page<ChronicDiseaseReimbursement> page = reimbursementService.getReimbursementPage(
                    current, size, farmerName, diseaseName, auditStatus);

            // 过滤符合条件的记录并设置农民姓名
            List<ChronicDiseaseReimbursement> filteredRecords = page.getRecords().stream()
                    .filter(record -> {
                        Farmer farmer = farmerService.getById(record.getFarmerId());
                        return farmer != null && farmer.getParentCode() != null &&
                                isValidRegionCode(userParentCode, farmer.getParentCode());
                    })
                    .peek(record -> {
                        Farmer farmer = farmerService.getById(record.getFarmerId());
                        if (farmer != null) {
                            record.setFarmerName(farmer.getName());
                        }
                    })
                    .collect(Collectors.toList());

            // 创建分页对象
            Page<ChronicDiseaseReimbursement> filteredPage = new Page<>(
                    page.getCurrent(),
                    page.getSize(),
                    filteredRecords.size()
            );
            filteredPage.setRecords(filteredRecords);

            // 按村和镇两级统计报销金额和数量
            Map<String, RegionStat> villageStats = new HashMap<>();
            Map<String, RegionStat> townStats = new HashMap<>();

            // 缓存已查询的行政区域信息
            Map<String, AdministrativeRegion> regionCache = new HashMap<>();

            for (ChronicDiseaseReimbursement record : filteredRecords) {
                Farmer farmer = farmerService.getById(record.getFarmerId());
                if (farmer != null && farmer.getParentCode() != null) {
                    String regionCode = farmer.getParentCode();

                    // 获取区域信息
                    AdministrativeRegion region = getRegionFromCache(regionCode, regionCache);

                    // 如果区域不存在，跳过该记录
                    if (region == null) {
                        continue;
                    }

                    // 根据区域级别进行不同处理
                    if (region.getLevel() == 3) {
                        // 村级区域，直接统计
                        String villageCode = regionCode;
                        String villageName = region.getRegionName();
                        String townCode = region.getParentCode();

                        // 获取镇信息
                        AdministrativeRegion townRegion = getRegionFromCache(townCode, regionCache);
                        String townName = townRegion != null ? townRegion.getRegionName() : "未知镇";

                        // 更新村统计
                        villageStats.computeIfAbsent(villageCode,
                                        k -> new RegionStat(villageCode, villageName, BigDecimal.ZERO, 0))
                                .addAmount(record.getReimbursementAmount())
                                .incrementCount();

                        // 更新镇统计
                        townStats.computeIfAbsent(townCode,
                                        k -> new RegionStat(townCode, townName, BigDecimal.ZERO, 0))
                                .addAmount(record.getReimbursementAmount())
                                .incrementCount();
                    } else if (region.getLevel() == 2) {
                        // 镇级区域，只统计镇
                        String townCode = regionCode; //编码
                        String townName = region.getRegionName(); //名称

                        // 更新镇统计
                        townStats.computeIfAbsent(townCode,
                                        k -> new RegionStat(townCode, townName, BigDecimal.ZERO, 0))
                                .addAmount(record.getReimbursementAmount()) //累计金额
                                .incrementCount(); //累计次数
                    }
                }
            }

            // 构建返回结果
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("page", filteredPage);
            resultMap.put("villageStats", villageStats.values());
            resultMap.put("townStats", townStats.values());

            return Result.success("慢病报销记录分页查询成功", resultMap);
        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "分页查询报销", "失败", e.getMessage());
            return Result.error("分页查询异常: " + e.getMessage());
        }
    }

    private AdministrativeRegion getRegionFromCache(String regionCode, Map<String, AdministrativeRegion> cache) {
        if (cache.containsKey(regionCode)) {
            return cache.get(regionCode);
        }

        AdministrativeRegion region = administrativeRegionService.getRegionByCode(regionCode);
        cache.put(regionCode, region);
        return region;
    }
    /**
     * 判断目标编码是否与源编码相同或为其子级
     */
    private boolean isValidRegionCode(String sourceCode, String targetCode) {
        // 如果两个编码完全相同，直接返回true
        if (sourceCode.equals(targetCode)) {
            return true;
        }

        // 判断targetCode是否是sourceCode的子级
        // 子级编码的前几位应该与父级编码相同
        return targetCode.startsWith(sourceCode);
    }
    @GetMapping("/list1")
    public Result<Map<String, Object>> getReimbursementPage1(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String farmerName,
            @RequestParam(required = false) String diseaseName,
            @RequestParam(required = false) String auditStatus,
            HttpServletRequest request) {
        try {
            // 从请求头中获取 Token
            String token = request.getHeader("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error("未授权访问");
            }

            token = token.substring(7); // 去掉 "Bearer " 前缀

            // 校验 token 有效性
            if (!StpUtil.isLogin()) {
                return Result.error("无效的 Token");
            }

            // 获取登录用户 ID
            Long userId = StpUtil.getLoginIdAsLong();

            // 从 Redis 中获取用户信息
            String userKey = "user:" + userId;
            User user = (User) redisTemplate.opsForValue().get(userKey);

            if (user == null) {
                return Result.error("用户信息不存在，请重新登录");
            }

            // 从用户信息中获取行政区域编码
            String userParentCode = user.getParentCode();
            if (userParentCode == null || userParentCode.isEmpty()) {
                return Result.error("用户行政区域编码不存在");
            }

            // 调用原有的分页查询方法获取基础数据
            Page<ChronicDiseaseReimbursement> page = reimbursementService.getReimbursementPage(
                    current, size, farmerName, diseaseName, auditStatus);

            // 过滤行政区域编码符合条件的记录
            List<ChronicDiseaseReimbursement> filteredRecords = page.getRecords().stream()
                    .filter(record -> {
                        // 通过 farmerId 获取农民信息
                        Farmer farmer = farmerService.getById(record.getFarmerId());
                        if (farmer == null || farmer.getParentCode() == null) {
                            return false;
                        }

                        // 判断农民的行政区域编码是否与用户的编码相同或为其子级
                        return isValidRegionCode(userParentCode, farmer.getParentCode());
                    })
                    .collect(Collectors.toList());

            // 创建新的分页对象，包含过滤后的记录
            Page<ChronicDiseaseReimbursement> filteredPage = new Page<>(
                    page.getCurrent(),
                    page.getSize(),
                    filteredRecords.size()
            );
            filteredPage.setRecords(filteredRecords);

            // 按病种类型进行分类统计
            Map<String, Map<String, Object>> diseaseStatistics = filteredRecords.stream()
                    .collect(Collectors.groupingBy(
                            ChronicDiseaseReimbursement::getDiseaseName, //根据疾病种类分组
                            Collectors.collectingAndThen(
                                    Collectors.toList(), //种类集合
                                    records -> {
                                        Map<String, Object> stats = new HashMap<>();
                                        stats.put("count", records.size()); //每个种类对应的数量
                                        stats.put("totalAmount", records.stream() //累加金额总数
                                                .map(ChronicDiseaseReimbursement::getReimbursementAmount)
                                                .reduce(BigDecimal.ZERO, BigDecimal::add));
                                        return stats;
                                    }
                            )
                    ));

            // 准备返回结果
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("page", filteredPage);
            resultMap.put("diseaseStatistics", diseaseStatistics);

            return Result.success("慢病报销记录分页查询及病种统计成功", resultMap);
        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "分页查询报销", "失败", e.getMessage());
            return Result.error("分页查询异常: " + e.getMessage());
        }
    }
    @PostMapping("/query")
    public Result<Page<ChronicDiseaseReimbursement>> queryReimbursements(
            @RequestBody ChronicDiseaseReimbursement queryParam,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<ChronicDiseaseReimbursement> page = reimbursementService.queryReimbursements(
                    queryParam, current, size);
            /*logUtils.recordLog("慢病报销管理", "条件查询报销", "成功",
                    "条件:" + queryParam.toString() + ", 页码:" + current + ", 大小:" + size);*/
            return Result.success("慢病报销记录条件查询成功", page);
        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "条件查询报销", "失败", e.getMessage());
            return Result.error("条件查询异常: " + e.getMessage());
        }
    }
    /**
     * 开始慢性病报销流程，验证农民是否参合
     */
    @PostMapping("/startReimbursement")
    public Result<Map<String, Object>> startReimbursement(@RequestParam String idCard) {
        try {
            // 1. 验证身份证号是否存在且已参合
            Farmer farmer = farmerService.getFarmerByIdCart(idCard);
            if (farmer == null) {
                logUtils.recordLog("慢病报销管理", "开始报销", "失败", "身份证号不存在: " + idCard);
                return Result.error("未找到该身份证号对应的农民信息");
            }

            if (farmer.getIsCooperative() == null || farmer.getIsCooperative() == 0) {
                logUtils.recordLog("慢病报销管理", "开始报销", "失败", "身份证号未参合: " + idCard);
                return Result.error("该农民未参加农村合作医疗，无法进行慢病报销");
            }

            if (farmer.getCoopStatus() != null && farmer.getCoopStatus() != 1) {
                String statusMsg = farmer.getCoopStatus() == 2 ? "停保" : "退保";
                logUtils.recordLog("慢病报销管理", "开始报销", "失败", "身份证号状态异常: " + idCard + ", 状态: " + statusMsg);
                return Result.error("该农民农合状态为" + statusMsg + "，无法进行慢病报销");
            }

            // 2. 获取农民的慢性病证信息
            List<ChronicDiseaseCertificate> certificates = certificateService
                    .queryChronicDiseaseCertificate(
                            new ChronicDiseaseCertificate().setFarmerId(farmer.getFarmerId()),
                            1, 100)
                    .getRecords();

            if (certificates.isEmpty()) {
                logUtils.recordLog("慢病报销管理", "开始报销", "失败", "身份证号无慢病证明: " + idCard);
                return Result.error("该农民没有有效的慢性病证明，无法进行慢病报销");
            }

            // 3. 获取当前年度的慢性病政策
            int currentYear = Calendar.getInstance().get(Calendar.YEAR);
            List<ChronicDiseasePolicy> policies = new ArrayList<>();
            for (ChronicDiseaseCertificate cert : certificates) {
                // 获取该疾病名称对应的所有政策列表
                List<ChronicDiseasePolicy> policyList = policyService.getChronicDiseasePolicyByDiseaseName(cert.getDiseaseName());
                if (policyList != null) {
                    // 筛选当前年份的政策
                    for (ChronicDiseasePolicy policy : policyList) {
                        if (policy != null && policy.getYear() != null && policy.getYear() == currentYear) {
                            policies.add(policy);
                        }
                    }
                }
            }

            if (policies.isEmpty()) {
                logUtils.recordLog("慢病报销管理", "开始报销", "失败", "无当前年度慢病政策: " + idCard);
                return Result.error("未找到当前年度的慢性病报销政策，请联系管理员");
            }

            // 4. 准备返回数据
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("farmerInfo", farmer);
            resultData.put("diseaseCertificates", certificates);
            resultData.put("currentPolicies", policies);

            // 5. 计算当年已报销金额
            BigDecimal totalReimbursed = reimbursementService.calculateAnnualReimbursement(
                    farmer.getFarmerId(), currentYear);
            resultData.put("annualReimbursedAmount", totalReimbursed);

            logUtils.recordLog("慢病报销管理", "开始报销", "成功", "身份证号: " + idCard);
            return Result.success("慢病报销流程已启动", resultData);

        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "开始报销", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    /**
     * 提交慢性病报销申请
     */
    @PostMapping("/submitReimbursement")
    public Result<Boolean> submitReimbursement(@RequestBody ChronicDiseaseReimbursement reimbursement) {
        try {
            // 1. 验证必填字段（仅保留关键字段）
            if (reimbursement.getFarmerId() == null) {
                logUtils.recordLog("慢病报销管理", "提交报销", "失败", "缺少农民ID");
                return Result.error("请选择参合农民");
            }

            if (reimbursement.getDiseaseName() == null || reimbursement.getReimbursementAmount() == null) {
                logUtils.recordLog("慢病报销管理", "提交报销", "失败", "缺少疾病名称或报销金额");
                return Result.error("请填写完整的报销信息");
            }

            // 2. 验证农民是否有效（简化版，仅检查是否存在）
            Farmer farmer = farmerService.getById(reimbursement.getFarmerId());
            if (farmer == null) {
                logUtils.recordLog("慢病报销管理", "提交报销", "失败", "无效的农民ID: " + reimbursement.getFarmerId());
                return Result.error("所选农民信息不存在");
            }

            // 3. 验证慢性病证信息（简化版，仅检查是否存在）
            ChronicDiseaseCertificate certificate = certificateService
                    .queryChronicDiseaseCertificate(
                            new ChronicDiseaseCertificate()
                                    .setFarmerId(reimbursement.getFarmerId())
                                    .setDiseaseName(reimbursement.getDiseaseName()),
                            1, 1)
                    .getRecords()
                    .stream()
                    .findFirst()
                    .orElse(null);

            if (certificate == null) {
                logUtils.recordLog("慢病报销管理", "提交报销", "失败",
                        "农民ID: " + reimbursement.getFarmerId() + " 无该疾病的慢病证明: " + reimbursement.getDiseaseName());
                return Result.error("该农民没有对应疾病的慢性病证明，无法报销");
            }

            // 4. 获取当前年度政策（简化版，直接获取不验证年份）
            List<ChronicDiseasePolicy> policyList = policyService.getChronicDiseasePolicyByDiseaseName(reimbursement.getDiseaseName());

            if (policyList == null || policyList.isEmpty()) {
                logUtils.recordLog("慢病报销管理", "提交报销", "失败",
                        "无该疾病的报销政策: " + reimbursement.getDiseaseName());
                return Result.error("未找到该疾病的报销政策");
            }

            // 5. 计算本次可报销金额（简化版，使用前端计算的金额）
            // 验证提交的报销金额是否合理
            if (reimbursement.getReimbursementAmount().compareTo(BigDecimal.ZERO) <= 0) {
                logUtils.recordLog("慢病报销管理", "提交报销", "失败",
                        "报销金额必须大于0: " + reimbursement.getReimbursementAmount());
                return Result.error("报销金额必须大于0");
            }

            // 6. 保存报销申请
            reimbursement.setAuditStatus("待审核");
            reimbursement.setRemittanceStatus("待汇款");
            reimbursement.setReimbursementTime(new Date());

            boolean result = reimbursementService.save(reimbursement);
            if (result) {
                logUtils.recordLog("慢病报销管理", "提交报销", "成功",
                        "农民ID:" + reimbursement.getFarmerId() + ", 疾病:" + reimbursement.getDiseaseName() +
                                ", 金额:" + reimbursement.getReimbursementAmount());
                return Result.success("慢病报销申请已提交，等待审核", true);
            } else {
                logUtils.recordLog("慢病报销管理", "提交报销", "失败", "保存数据库失败");
                return Result.error("慢病报销申请提交失败");
            }

        } catch (Exception e) {
            logUtils.recordLog("慢病报销管理", "提交报销", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }
}
